package cn.chen.hd.fs;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.*;
import org.apache.hadoop.util.ReflectionUtils;

import java.io.IOException;
import java.net.URI;

public class SequenceFileTest {

    private static final String[] text = {
      "两行黄鹂名翠柳",
      "一行白鹭上青天",
      "窗含西岭千秋雪",
      "门泊东吴万里船"
    };

    public static void main(String[] args) {
        SequenceFileTest.read();
    }

    public static void read(){
        String uri = "hdfs://localhost:9000/chen/testeq";
        Configuration conf = new Configuration();
        SequenceFile.Reader reader = null;

        try {
            FileSystem fs = FileSystem.get(URI.create(uri), conf);
            reader = new SequenceFile.Reader(fs, new Path(uri), conf);
            Writable key = (Writable) ReflectionUtils.newInstance(reader.getKeyClass(), conf);
            Writable value = (Writable) ReflectionUtils.newInstance(reader.getValueClass(), conf);
            long position = reader.getPosition();
            while(reader.next(key, value)){
                System.out.printf("[%s]\t%s\n",key,value);
                position = reader.getPosition();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            IOUtils.closeStream(reader);
        }
    }

    public static void write(){
        String uri = "hdfs://localhost:9000/chen/testeq";
        Configuration conf = new Configuration();
        SequenceFile.Writer writer = null;

        try {
            FileSystem fs = FileSystem.get(URI.create(uri), conf);
            IntWritable key = new IntWritable();
            Text value = new Text();
            writer = SequenceFile.createWriter(fs, conf,new Path(uri)
                    ,key.getClass(),value.getClass());
            for(int i = 0;i < 100;i ++){
                key.set(100 - i);
                value.set(text[i%text.length]);
                writer.append(key, value);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            IOUtils.closeStream(writer);
        }
    }

}
